package com.doyens.item.service;


import com.doyens.common.pojo.PageResult;
import com.doyens.item.dto.SpuDTO;
import com.doyens.item.mapper.*;
import com.doyens.item.pojo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;


import java.util.Arrays;
import java.util.Date;
import java.util.List;

import java.util.stream.Collectors;

@Service
public class GoodsService {

    @Autowired
    private SpuMapper  spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private BrandMapper  brandMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private static final Logger LOGGER = LoggerFactory.getLogger(GoodsService.class);


    public PageResult<SpuDTO> querySpuByPage(String key, Boolean saleable, Integer page, Integer rows) {

        //添加查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }
        //添加上下架过滤条件
        if (saleable !=null){
            criteria.andEqualTo("saleable",saleable);
        }
        //添加分页
        PageHelper.startPage(page,rows);


        //执行查询,获取spu集合
        List<Spu> spus = this.spuMapper.selectByExample(example);
        //spu集合转换成spuDTO
        List<SpuDTO> spuDTOList = spus.stream().map(spu -> {
            SpuDTO  spuDTO = new SpuDTO();
            BeanUtils.copyProperties(spu,spuDTO);  //把spu对象中的数据复制到spudto对象中
            Brand brand = this.brandMapper.selectByPrimaryKey(spu.getBrandId());
            spuDTO.setBname(brand.getName());//品牌信息
            List<String> names = this.categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuDTO.setCname(StringUtils.join(names,"-"));  //手机-手机通讯-手机
            return spuDTO;
        }).collect(Collectors.toList());
        //返回pageResult<SpuDTO>

        PageInfo<Spu> pageInfo = new PageInfo<>(spus);
        return  new PageResult<>(pageInfo.getTotal(),spuDTOList);
    }

    /**
     * 保存商品
     * @param spuDTO
     */
    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        //先新增spu
        spuDTO.setId(null);
        spuDTO.setCreateTime(new Date());
        spuDTO.setLastUpdateTime(spuDTO.getCreateTime());
        spuDTO.setValid(true);//是否有效
        spuDTO.setSaleable(true);//是否上架
        this.spuMapper.insertSelective(spuDTO);
        //再去新增spudetail
        SpuDetail spuDetail = spuDTO.getSpuDetail();
        spuDetail.setSpuId(spuDTO.getId());
        this.spuDetailMapper.insertSelective(spuDetail);
        saveSku(spuDTO);
        //发送的消息

        sendMessage("insert",spuDTO.getId());


    }

    //发送消息  方法
    private void sendMessage(String type, Long spuId) {
        try {

            this.amqpTemplate.convertAndSend("item."+type,spuId);
        }catch (AmqpException e){
            e.printStackTrace();
            LOGGER.error("添加商品发送rabbimq消息失败{}",e.getMessage());
        }
    }

    //新增sku信息
    private void saveSku(SpuDTO spuDTO){
        spuDTO.getSkus().forEach(sku ->{
            //新增sku
            sku.setId(null);
            sku.setSpuId(spuDTO.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insertSelective(sku);
            //新增  stock
            Stock stock = new Stock();
            stock.setStock(sku.getStock());
            stock.setSkuId(sku.getId());
            this.stockMapper.insertSelective(stock);
        });
    }


    /**
     * 查询 商品详情
     * @param spuId
     * @return
     */
    public SpuDetail querySpuDataiBySpuId(Long spuId) {
        return this.spuDetailMapper.selectByPrimaryKey(spuId);
    }

    /**
     * 查询sku列表
     * @param id
     * @return
     */
    public List<Sku> querySkusBySpuId(Long id) {
        Sku record = new Sku();
        record.setSpuId(id);
        List<Sku> skus = this.skuMapper.select(record);
        skus.forEach(sku -> {
            Stock stock = this.stockMapper.selectByPrimaryKey(sku.getId());
            sku.setStock(stock.getStock());//库存信息
        });
        return skus;
    }


    //修改商品信息
    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        //sku表和stock库存表信息的处理  直接删除  再重新添加
        //先根据spuid查询要删除的skuid
        Sku record = new Sku();
        record.setSpuId(spuDTO.getId());
        List<Sku> skus = this.skuMapper.select(record);
        skus.forEach(sku -> {
            //删除stock
            this.stockMapper.deleteByPrimaryKey(sku.getId());
        });
        //删除sku
        Sku  sku = new Sku();
        sku.setSpuId(spuDTO.getId());
        this.skuMapper.delete(sku);
        //新增sku
        //新增stock
        saveSku(spuDTO);
        //修改 spu表和detail
        spuDTO.setCreateTime(null);
        spuDTO.setLastUpdateTime(new Date());//最后修改时间
        spuDTO.setValid(null);
        spuDTO.setSaleable(null);
        this.spuMapper.updateByPrimaryKeySelective(spuDTO);
        this.spuDetailMapper.updateByPrimaryKeySelective(spuDTO.getSpuDetail());

        sendMessage("update",spuDTO.getId());//发送消息
    }

    public Spu querySpuById(Long id) {
        return this.spuMapper.selectByPrimaryKey(id);
    }

    public Sku queryBySkuId(Long skuId) {
        return this.skuMapper.selectByPrimaryKey(skuId);
    }
}
